// @flow
import React from 'react'
import styles from './CmPage.css'
import { Form, Input, Button, Tooltip, Icon } from 'antd'
import CmList from './CmList'
import NoticeMessage from '../NoticeMessage'
const FormItem = Form.Item
type Props = {
  form: Object,
  nextStep: Function,
  storeCmData: Function
}
type State = {
  data: Object,
  disabled: boolean
}
class CmPage extends React.Component {
  props: Props
  state: State
  nextClick: () => void
  handleSubmit: () => void
  connectTest: () => void
  constructor (props: Props) {
    super(props)
    this.state = {
      data: {},
      disabled: true
    }
    this.connectTest = this.connectTest.bind(this)
    this.nextClick = this.nextClick.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }
  componentDidMount () {
    console.info(this.props)
  }

  nextClick () {
    this.handleSubmit('checked')
  }

  handleSubmit (method) {
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.info(err)
      console.log('Received values of form: ', values)
      const connectTest = () => {
        let strArr = []
        for (let key in values) {
          if (values[key]) {
            strArr.push(`${key}=${values[key]}`)
          }
        }
        console.info(strArr.join('&'))
        this.connectTest(strArr.join('&'))
      }
      if (err && !err.hasOwnProperty('ip')) {
        connectTest()
      }
      if (!err) {
        connectTest()
        if (method === 'checked') {
          let cmApi = {}
          cmApi.ipAddress = values.ip
          cmApi.port = parseInt(values.port)
          cmApi.username = values.username
          cmApi.password = values.password
          console.info(JSON.stringify(cmApi, null, 4))
          this.props.storeCmData(cmApi)
          this.props.nextStep(2)
        }
      }
    })
  }

  connectTest (query) {
    const url = `${__CM_URL__}cm/services?${query}`
    fetch(url)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      console.info('result:', json)
      if (json.code === 1 || json.code === -1) {
        throw new Error(json.message, 'CmPage.js')
      }
      this.setState({
        data: json.body,
        disabled: false
      })
    })
    .catch((err) => {
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
      this.setState({ disabled: true })
      console.error(err)
    })
  }

  ipCheck (rule, value, callback) {
    const reg = /((?:(?:25[0-5]|2[0-4]\d|(?:1\d{2}|[1-9]?\d))\.){3}(?:25[0-5]|2[0-4]\d|(?:1\d{2}|[1-9]?\d)))/
    if (value && !reg.test(value)) {
      callback(new Error('请输入正确的IP地址'))
    } else {
      callback()
    }
  }

  portCheck (rule, value, callback) {
    const reg = /^[0-9]*$/
    if (value && !reg.test(value)) {
      callback(new Error('请输入正确的端口'))
    } else {
      callback()
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { data, disabled } = this.state
    const formLayout = {
      labelCol: { span: 11 },
      wrapperCol: { span: 13 }
    }
    return (
      <div className={styles['content']}>
        <Form>
          <FormItem
            {...formLayout}
            label={(
              <span>
                Cloudera Manger Server | 地&emsp;址&nbsp;
                <Tooltip title='eg:192.168.130.33'>
                  <Icon type='question-circle-o' />
                </Tooltip>
              </span>
            )}
          >
            {getFieldDecorator('ip', {
              rules: [{ required: true, message: '请输入IP地址' }, {
                validator: this.ipCheck
              }],
              initialValue: '192.168.130.33'
            })(
              <Input />
            )}
          </FormItem>
          <FormItem
            {...formLayout}
            label={(
              <span>
                Cloudera Manger Server | 端&emsp;口&nbsp;
                <Tooltip title='eg:7180'>
                  <Icon type='question-circle-o' />
                </Tooltip>
              </span>
            )}
          >
            {getFieldDecorator('port', {
              rules: [
                { required: true, message: '请输入端口！' },
                {
                  validator: this.portCheck
                }],
              initialValue: '7180'
            })(
              <Input />
            )}
          </FormItem>
          <FormItem
            {...formLayout}
            label={(
              <span>
                Cloudera Manger Server | 用户名&nbsp;
                <Tooltip title='eg:amin'>
                  <Icon type='question-circle-o' />
                </Tooltip>
              </span>
            )}
          >
            {getFieldDecorator('username', {
              rules: [
                { required: true, message: '请输入用户名!' }
              ],
              initialValue: 'admin'
            })(
              <Input />
            )}
          </FormItem>
          <FormItem
            {...formLayout}
            label={(
              <span>
                Cloudera Manger Server | 密&emsp;码&nbsp;
                <Tooltip title='eg:amin'>
                  <Icon type='question-circle-o' />
                </Tooltip>
              </span>
            )}
          >
            {getFieldDecorator('password', {
              rules: [
                { required: true, message: '请输入密码!' }
              ],
              initialValue: 'admin'
            })(
              <Input type='password' />
            )}
          </FormItem>
        </Form>
        <div className={styles['table']}>
          <CmList data={data} />
        </div>
        <div className={styles['btnControl']}>
          <div className={styles['left']}>
            <Button type='primary' onClick={this.handleSubmit}>连接测试</Button>
          </div>
          <div className={styles['right']}>
            <Button onClick={this.nextClick} disabled={disabled}>下一步</Button>
          </div>
        </div>
      </div>
    )
  }
}

export default Form.create()(CmPage)
